package com.ficus.road.maintain.core.infrastructure.mongo;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class MongoDao {
    private MongoCollection<Document> mongoCollection;

    public MongoDao(MongoCollection<Document> mongoCollection) {
        this.mongoCollection = mongoCollection;
    }

    public MongoDao(String host, int port, String database, String collection) {
        MongoClient mongoClient = new MongoClient(host , port);
        MongoDatabase mongoDatabase = mongoClient.getDatabase(database);
        this.mongoCollection = mongoDatabase.getCollection(collection);
    }

    public List<Document> find() {
        FindIterable<Document> findIterable = mongoCollection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        List<Document> result = new ArrayList<>();
        while(mongoCursor.hasNext()) {
            result.add(mongoCursor.next());
        }
        return result;
    }

    public void insert(Document document) {
        mongoCollection.insertOne(document);
    }
}
